package com.link.base.base.approval.service;

import com.link.base.base.accnt.dao.mybatis.mapper.AccountMapper;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.approval.dao.mybatis.mapper.FlowMapper;
import com.link.base.base.approval.exception.ApprovalNeedUserException;
import com.link.base.base.approval.exception.ApprovalNotNeedUserException;
import com.link.base.base.approval.model.*;
import com.link.base.base.message.push.service.PushService;
import com.link.base.base.position.dao.mybatis.mapper.PositionMapper;
import com.link.base.base.position.model.Position;
import com.link.base.base.user.model.User;
import com.link.base.base.user.service.UserService;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.dao.KeyGenerateDao;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.query.Sorter;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.LovUtil;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Copyright  hande Company. All Rights Reserved.
 *
 * @author unknwon
 * @version 1.0
 * @date: 2018/11/8 14:59
 */

@Service
public class FlowServiceImpl extends BasicServiceImpl<Flow> implements FlowService {

    @Resource
    private FlowMapper flowMapper;

    @Resource
    private ApprovalNodeService approvalNodeService;

    @Resource
    private FlowRecordService flowRecordService;

    @Resource
    private ApprovalService approvalService;

    @Resource
    private ApprovalOperateService approvalOperateService;

    @Resource
    private UserService userService;

    @Resource
    private FlowUserService flowUserService;

    @Resource
    private KeyGenerateDao keyGenerateDao;

    @Resource
    private PushService pushService;

    @Resource
    private UsersSelectService usersSelectService;

    @Resource
    private PositionMapper positionMapper;

    @Resource
    private AccountMapper accountMapper;

    /** 运行状态 */
    public static final String FLOW_STATUS_RUNNING = "Running";

    @Override
    public BasicMapper<Flow> getBasicMapper() throws Exception {
        return flowMapper;
    }

    /**
     * 分页查询活动信息
     */
    @Override
    public List<Flow> queryFlowListPage(Flow record) throws Exception {

        return flowMapper.queryFlowListPage(record);
    }


    @Override
    public List<Flow> queryMyFlowListPage(Flow record) throws Exception {
        //按创建时间来排序
        record.setAttr1(String.valueOf(UserUtil.getUser().getId()));
        return flowMapper.queryMyFlowListPage(record);
    }

    @Override
    public List<Flow> queryMyRunFlowListPage(Flow record) throws Exception {
        //按创建时间来排序
        record.setAttr1(String.valueOf(UserUtil.getUser().getId()));
        record.setFlowStatus(FLOW_STATUS_RUNNING);
        return flowMapper.queryMyRunFlowListPage(record);
    }

    @Override
    public void withdrawApproval(Long flowId, String comments, OtherFlowInfo otherInfo) throws Exception {
        //1、校验审批头
        Flow record = vertifyFlowHeader(flowId);

        /*审批流程的客户id*/
        Long accntId = record.getAccntId();

        //2、校验并获取审核节点
        ApprovalNode currentApprovalNode = vertifyApprovalNode(record, record.getApprovalNodeId(),"Withdraw");

        //当前节点撤回
        if (vertifyCurrentNodeRefuse(flowId, record)) {
            String nextNodeSn = null;

            //4.1、确定是否满足条件，并执行回调函数
            if (currentApprovalNode.getWithdrawFunId() != null) {
                approvalOperateService.doOperateService(record,
                        currentApprovalNode.getWithdrawFunId(), nextNodeSn);
            }

            //4.2、修改审核头上的下级审批信息
            //审批流程结束
            //下级审批人为空、状态改为已终止、处理人为空
            record.setApprovalNodeId(0L);
            record.setFlowNodePsnId(0L);
            record.setFlowStatus(LovUtil.getLovName("FLOW_STATUS", "Invalid"));
            flowMapper.finishFlowUpdate(record);

            //删除审批用户信息
            flowUserService.deleteByFlowId(flowId);
            //推送消息
            pushService
                    .sampleMessageForModule("审批撤回:" + record.getFlowName(), record.getFlowStartPsnId(),
                            flowId, "Withdraw");

        }

        //4.3、插入审记录
        flowRecordService.flowRecordInsert(flowId, currentApprovalNode.getId(), "审批撤回", comments);
    }

    /**
     * 分页查询活已流程
     */

    @Override
    public List<Flow> queryFlowedListPage(Flow record) throws Exception {

        return flowMapper.queryFlowedListPage(record);
    }


    /**
     * 根据流程记录对象id查询流程
     */
    @Override
    public List<Flow> queryFlowByObjId(Flow record) throws Exception {
        return flowMapper.queryFlowByObjId(record);
    }


    @Override
    public void nextNodeUpdate(Flow record) throws ServiceException, Exception {
        flowMapper.nextNodeUpdate(record);
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void agreeApproval(Long flowId, String comments, Long userId,
                              OtherFlowInfo otherInfo) throws ApprovalNeedUserException, Exception {
        //1、校验审批头
        Flow record = vertifyFlowHeader(flowId);

        /*审批流程的客户id*/
        Long accntId = record.getAccntId();

        //2、校验并获取审核节点
        ApprovalNode currentApprovalNode = vertifyApprovalNode(flowId, record.getApprovalNodeId());

        //3、其他审批操作
        if (currentApprovalNode.getOtherFunId() != null) {
            if (otherInfo == null) {
                throw new ServiceException("APPROVAL-014");
            }
            if (currentApprovalNode.getOtherFunId() == null) {
                throw new ServiceException("APPROVAL-015");
            }
            approvalOperateService
                    .doOtherOperate(record.getFlowObjId(), currentApprovalNode.getOtherFunId(),
                            otherInfo);
        }

        //4.0、确定是否整体审核通过
        if (vertifyCurrentNodeFinished(flowId, record)) {
            //查找下一节点序号
            String zero = "0";
            String nextNodeSn = approvalOperateService
                    .getDecideWithNextNodeNo(record.getFlowObjId(),
                            currentApprovalNode.getDecideFunId());
            if (nextNodeSn == null || zero.equals(nextNodeSn) || "".equals(nextNodeSn)) {
                nextNodeSn = currentApprovalNode.getNextSN();
            }

            if (currentApprovalNode.getSuccessCallFunId() != null) {
                approvalOperateService.doOperateService(record,
                        currentApprovalNode.getSuccessCallFunId(), nextNodeSn);
            }

            //4.2、修改审核头上的下级审批信息
            if (nextNodeSn != null && !"".equals(nextNodeSn)) {
                //流转下一审批节点
                ApprovalNode entity = new ApprovalNode();
                entity.setApprovalId(record.getApprovalId());
                entity.setSn(nextNodeSn);
                entity.setPageFlag(false);
                List<ApprovalNode> approvalNodeList = approvalNodeService
                        .queryByExamplePage(entity);
                if (approvalNodeList == null || approvalNodeList.size() == 0) {
                    throw new ServiceException("APPROVAL-016");
                } else if (approvalNodeList.size() > 1) {
                    throw new ServiceException("APPROVAL-017");
                }

                //重置审核用户信息
                List<User> userList = getNodeUserList(approvalNodeList.get(0), accntId);
                if (userList == null || userList.size() == 0) {
                    throw new ServiceException("APPROVAL-018");
                }
                String flag = "Y";
                //判断是否需要选择用户
                if (flag.equalsIgnoreCase(approvalNodeList.get(0).getMustSelectUser())) {
                    if (userId == null) {
                        throw new ApprovalNeedUserException("必须选择用户！["
                                + UserUtil.getUser().getId() + "],["
                                + approvalNodeList.get(0).getId() + "]");
                    }
                    boolean containUser = false;
                    for (User user : userList) {
                        if (user.getId().equals(userId)) {
                            containUser = true;
                        }
                    }
                    if (!containUser) {
                        throw new ServiceException("APPROVAL-019");
                    }
                } else {
                    if (userId != null) {
                        throw new ApprovalNotNeedUserException("不需要选择用户！");
                    }
                }

                flowUserService.deleteByFlowId(flowId);
                if (flag.equalsIgnoreCase(approvalNodeList.get(0).getMustSelectUser())) {
                    //下一审批人
                    record.setFlowNodePsnId(userId);
                    flowUserService.insert(userId, flowId, null);
                    //推送消息
                    pushService.sampleMessageForModule("请您审批:" + record.getFlowName(), userId, flowId,"Pending");
                } else {
                    //下一审批人
                    record.setFlowNodePsnId(userList.get(0).getId());
                    for (User userEntity : userList) {
                        flowUserService.insert(userEntity.getId(), flowId, null);
                        //推送消息
                        pushService
                                .sampleMessageForModule("请您审批:" + record.getFlowName(), userEntity.getId(),
                                        flowId, "Pending");
                    }
                }
                //更新下个审批节点、处理人信息
                record.setApprovalNodeId(approvalNodeList.get(0).getId());
                nextNodeUpdate(record);
            } else {
                //审批流程结束
                //下级审批人为空、状态改为已结束、处理人为空
                record.setApprovalNodeId(0L);
                record.setFlowNodePsnId(0L);
                record.setFlowStatus(LovUtil.getLovName("FLOW_STATUS", "End"));
                flowMapper.finishFlowUpdate(record);
                //删除审批用户信息
                flowUserService.deleteByFlowId(flowId);
                //推送消息
                pushService
                        .sampleMessageForModule("审批完成:" + record.getFlowName(), record.getFlowStartPsnId(),
                                flowId, "Approved");
            }

        }

        //5、插入审批历史记录
        flowRecordService.flowRecordInsert(flowId, currentApprovalNode.getId(), "审批通过", comments);
    }


    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void endApproval(Long flowId, String comments, OtherFlowInfo otherInfo)
            throws Exception {
        //1、校验审批头
        Flow record = vertifyFlowHeader(flowId);

        //2、校验并获取审核节点
        ApprovalNode currentApprovalNode = vertifyApprovalNode(flowId, record.getApprovalNodeId());
        //校验审批节点是否允许结束
        String flag = "Y";
        if (!flag.equalsIgnoreCase(currentApprovalNode.getAllowEnd())) {
            throw new ServiceException("APPROVAL-020");
        }

        //3、其他审批操作
        if (currentApprovalNode.getOperateUrl() != null) {
            if (otherInfo == null) {
                throw new ServiceException("APPROVAL-014");
            }
            if (currentApprovalNode.getOtherFunId() == null) {
                throw new ServiceException("APPROVAL-015");
            }
            approvalOperateService
                    .doOtherOperate(record.getFlowObjId(), currentApprovalNode.getOtherFunId(),
                            otherInfo);
        }

        if (currentApprovalNode.getSuccessCallFunId() != null) {
            approvalOperateService
                    .doOperateService(record, currentApprovalNode.getSuccessCallFunId(),
                            null);
        }

        //审批流程结束
        //下级审批人为空、状态改为已结束、处理人为空
        record.setApprovalNodeId(0L);
        record.setFlowNodePsnId(0L);
        record.setFlowStatus(LovUtil.getLovName("FLOW_STATUS", "End"));
        flowMapper.finishFlowUpdate(record);
        //删除审批用户信息
        flowUserService.deleteByFlowId(flowId);
        //推送消息
        pushService.sampleMessageOnlyUser("审批完成:" + record.getFlowName(), record.getFlowStartPsnId());

        //5、插入审批历史记录
        flowRecordService
                .flowRecordInsert(flowId, currentApprovalNode.getId(), "审批通过并结束流程", comments);
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void refuseApproval(Long flowId, String comments) throws Exception {
        //1、校验审批头
        Flow record = vertifyFlowHeader(flowId);

        /*审批流程的客户id*/
        Long accntId = record.getAccntId();

        //2、校验并获取审核节点
        ApprovalNode currentApprovalNode = vertifyApprovalNode(flowId, record.getApprovalNodeId());

        //当前节点拒绝
        if (vertifyCurrentNodeRefuse(flowId, record)) {
            String nextNodeSn = currentApprovalNode.getRefuseSN();

            //4.1、确定是否满足条件，并执行回调函数
            if (currentApprovalNode.getRefuseCallFunId() != null) {
                approvalOperateService.doOperateService(record,
                        currentApprovalNode.getRefuseCallFunId(), nextNodeSn);
            }

            //4.2、修改审核头上的下级审批信息
            if (nextNodeSn != null && !"".equals(nextNodeSn)) {
                //通过节点序号查找审批节点Id
                QueryParams qps = new QueryParams();
                qps.addFilter(new Filter("approvalId", String.valueOf(record.getApprovalId())));
                qps.addFilter(new Filter("sn", currentApprovalNode.getRefuseSN()));
                ApprovalNode t = (ApprovalNode) BasicModel.transformClass(ApprovalNode.class, qps);
                t.setPageFlag(false);
                List<ApprovalNode> approvalNodeList = approvalNodeService.queryByExamplePage(t);
                if (approvalNodeList == null || approvalNodeList.size() == 0) {
                    throw new ServiceException("APPROVAL-016");
                } else if (approvalNodeList.size() > 1) {
                    throw new ServiceException("APPROVAL-017");
                }
                ApprovalNode approvalNode = approvalNodeList.get(0);
                Long refuseNodeId = approvalNode.getId();
                //在该流程的审批历史中查找是否存在该节点审批历史
                QueryParams queryPars = new QueryParams();
                queryPars.setAttr1(String.valueOf(flowId));
                queryPars.addFilter(new Filter("approvalNodeId", String.valueOf(refuseNodeId)));
                Sorter sorter = new Sorter("created", Sorter.DIR_DESC);
                queryPars.addSorter(sorter);
                queryPars.setPageFlag(false);
                FlowRecord flowRecord = (FlowRecord) BasicModel
                        .transformClass(FlowRecord.class, queryPars);
                List<FlowRecord> flowRecordList = flowRecordService.queryByExamplePage(flowRecord);
                //流程不存在该节点的审批历史
                if (flowRecordList == null || flowRecordList.size() == 0) {
                    //重置审核用户信息
                    List<User> userList = getNodeUserList(approvalNode, accntId);
                    if (userList == null || userList.size() == 0) {
                        throw new ServiceException("APPROVAL-018");
                    }
                    flowUserService.deleteByFlowId(flowId);
                    for (User userEntity : userList) {
                        flowUserService.insert(userEntity.getId(), flowId, null);
                        //推送消息
                        pushService.sampleMessageForModule("请您审批:" + record.getFlowName(), userEntity.getId(), flowId, "Pending");
                    }
                    //更新下个审批节点、处理人信息
                    record.setApprovalNodeId(approvalNode.getId());
                    record.setFlowNodePsnId(userList.get(0).getId());
                    nextNodeUpdate(record);
                } else { //流程存在该节点的审批历史
                    FlowRecord refuseFlowRecord = flowRecordList.get(0);
                    Long userId = refuseFlowRecord.getApprovalUserId();
                    if (null == userId) {
                        throw new ServiceException("APPROVAL-021");
                    }
                    //验证该审批人是否存在(当时存在后面被删除)
                    User entity = new User();
                    entity.setId(userId);
                    User recordOne = userService.queryById(entity);
                    if (recordOne == null) {
                        throw new ServiceException("APPROVAL-022");
                    }
                    //删除流程用户
                    flowUserService.deleteByFlowId(flowId);
                    //推送流程用户、插入流程用户表
                    flowUserService.insert(userId, flowId, null);
                    //推送消息
                    pushService
                        .sampleMessageForModule("请您审批:" + record.getFlowName(), userId, flowId, "Pending");
                    //更新流程下级节点、下级审批人
                    //更新下个审批节点、处理人信息
                    record.setApprovalNodeId(approvalNode.getId());
                    record.setFlowNodePsnId(userId);
                    nextNodeUpdate(record);
                }
            } else {
                //审批流程结束
                //下级审批人为空、状态改为已终止、处理人为空
                record.setApprovalNodeId(0L);
                record.setFlowNodePsnId(0L);
                record.setFlowStatus(LovUtil.getLovName("FLOW_STATUS", "Invalid"));
                flowMapper.finishFlowUpdate(record);

                //删除审批用户信息
                flowUserService.deleteByFlowId(flowId);
                //推送消息
                pushService
                    .sampleMessageForModule("审批拒绝:" + record.getFlowName(), record.getFlowStartPsnId(),
                        flowId, "Rejected");
            }
            //4.2、审批拒绝
        }

        //4.3、插入审记录
        flowRecordService.flowRecordInsert(flowId, currentApprovalNode.getId(), "审批拒绝", comments);
    }

    /**
     * &#x6821;&#x9a8c;&#x5f53;&#x524d;&#x8282;&#x70b9;&#x662f;&#x5426;&#x6574;&#x4f53;&#x5ba1;&#x6838;&#x7ed3;&#x675f;
     */
    private boolean vertifyCurrentNodeRefuse(Long flowId, Flow flow) throws Exception {
        flow.setCurrentDesc("");
        return true;
    }

    /**
     * 校验当前节点是否整体审核通过
     */
    private boolean vertifyCurrentNodeFinished(Long flowId, Flow flow) throws Exception {
        return true;
    }

    /**
     * 校验当前审核节点信息，并返回当前节点
     */
    private ApprovalNode vertifyApprovalNode(Long flowId, Long approvalNodeId)
            throws Exception {
        CoreUser currentUser = UserUtil.getUser();
        //1、校验节点信息
        ApprovalNode nodeExample = new ApprovalNode();
        nodeExample.setId(approvalNodeId);
        ApprovalNode approvalNode = approvalNodeService.queryById(nodeExample);
        if (approvalNode == null) {
            throw new ServiceException("APPROVAL-023");
        }

        //2、当前节点，本用户、本次是否已经审核过
        List<FlowUser> userList = flowUserService.queryByFLowId(flowId);
        if (userList == null || userList.size() == 0) {
            throw new ServiceException("APPROVAL-019");
        }
        //2.1存在审批操作为空的数据
        boolean needsOperate = false;
        for (int i = 0; i < userList.size(); i++) {
            FlowUser flowUser = userList.get(i);
            if (currentUser.getId().equals(flowUser.getUserId())) {
                if (flowUser.getOperate() == null || "".equals(flowUser.getOperate())) {
                    needsOperate = true;
                }
            }
        }
        if (!needsOperate) {
            throw new ServiceException("APPROVAL-024");
        }
        return approvalNode;
    }

    /**
     * 校验当前审核节点信息，并返回当前节点
     */
    private ApprovalNode vertifyApprovalNode(Long flowId, Long approvalNodeId,String type)
            throws Exception {

        CoreUser currentUser = UserUtil.getUser();
        //1、校验节点信息
        ApprovalNode nodeExample = new ApprovalNode();
        nodeExample.setId(approvalNodeId);
        ApprovalNode approvalNode = approvalNodeService.queryById(nodeExample);
        if (approvalNode == null) {
            throw new ServiceException("APPROVAL-023");
        }

        //2、当前节点，本用户、本次是否已经审核过
        List<FlowUser> userList = flowUserService.queryByFLowId(flowId);
        if (userList == null || userList.size() == 0) {
            throw new ServiceException("APPROVAL-019");
        }
        //2.1存在审批操作为空的数据
        boolean needsOperate = false;
        if ("Withdraw".equals(type)) {
            System.out.println(currentUser.getId() + "//////////" + approvalNode.getCreatedBy());
            if (currentUser.getId().equals(approvalNode.getCreatedBy())) {
                needsOperate = true;
            }
        } else {
            for (int i = 0; i < userList.size(); i++) {
                FlowUser flowUser = userList.get(i);
                if (currentUser.getId().equals(flowUser.getUserId())) {
                    if (flowUser.getOperate() == null || "".equals(flowUser.getOperate())) {
                        needsOperate = true;
                    }
                }
            }
        }
        if (!needsOperate) {
            throw new ServiceException("APPROVAL-024");
        }

        return approvalNode;
    }

    /**
     * 校验当前审核节点信息，并返回当前节点
     */
    private ApprovalNode vertifyApprovalNode(Flow flow, Long approvalNodeId,String type)
            throws Exception {

        CoreUser currentUser = UserUtil.getUser();
        long flowId = flow.getId();
        //1、校验节点信息
        ApprovalNode nodeExample = new ApprovalNode();
        nodeExample.setId(approvalNodeId);
        ApprovalNode approvalNode = approvalNodeService.queryById(nodeExample);
        if (approvalNode == null) {
            throw new ServiceException("APPROVAL-023");
        }

        //2、当前节点，本用户、本次是否已经审核过
        List<FlowUser> userList = flowUserService.queryByFLowId(flowId);
        if (userList == null || userList.size() == 0) {
            throw new ServiceException("APPROVAL-019");
        }
        //2.1存在审批操作为空的数据
        boolean needsOperate = false;
        if ("Withdraw".equals(type)) {
            if (currentUser.getId().equals(flow.getCreatedBy())) {
                needsOperate = true;
            }
        }
        if (!needsOperate) {
            throw new ServiceException("APPROVAL-024");
        }

        return approvalNode;
    }

    /**
     * 校验审核头信息，并返回审核头
     */
    private Flow vertifyFlowHeader(Long flowId) throws Exception {
        if (flowId == null) {
            throw new ServiceException("审批" + "PUBLIC-007");
        }
        Flow example = new Flow();
        example.setId(flowId);
        Flow record = queryById(example);
        if (record == null) {
            throw new ServiceException("APPROVAL-025");
        }
        String running = "Running";
        String flowStatus = "FLOW_STATUS";
        if (!running.equals(record.getFlowStatus())) {
            throw new ServiceException("APPROVAL-026");
        }
        //校验审批头上，审批对象ID
        if (record.getFlowObjId() == null) {
            throw new ServiceException("APPROVAL-027");
        }
        if (record.getApprovalId() == null) {
            throw new ServiceException("APPROVAL-028");
        }
        return record;
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void goApproval(Long flowId, String comments, Long userId) throws Exception {
        User example = new User();
        example.setId(userId);
        User otherUser = userService.queryById(example);
        if (otherUser == null) {
            throw new ServiceException("APPROVAL-029");
        }

        //1、校验审批头
        Flow record = vertifyFlowHeader(flowId);

        //2、校验并获取审核节点
        ApprovalNode currentApprovalNode = vertifyApprovalNode(flowId, record.getApprovalNodeId());
        //校验审批节点是否允许转交
        String flag = "Y";
        if (!flag.equalsIgnoreCase(currentApprovalNode.getAllowTransfer())) {
            throw new ServiceException("APPROVAL-030");
        }

        //3、更改当前审批人节点信息，新增转交人审批
        CoreUser currentUser = UserUtil.getUser();
        List<FlowUser> userList = flowUserService.queryByFLowId(flowId);

        FlowUser flowUser = null;
        for (int i = 0; userList != null && i < userList.size(); i++) {
            flowUser = userList.get(i);
            if (currentUser.getId().equals(flowUser.getUserId())) {
                if (flowUser.getOperate() == null || "".equals(flowUser.getOperate())) {
                    break;
                }
            }
            flowUser = null;
        }
        if (flowUser == null) {
            throw new ServiceException("APPROVAL-031");
        }
        flowUserService.update(flowUser.getId(), "3");
        flowUserService.insert(userId, flowId, null);

        //更新当前节点：处理人信息
        record.setApprovalNodeId(record.getApprovalNodeId());
        record.setFlowNodePsnId(userId);
        nextNodeUpdate(record);

        //审批历史
        flowRecordService.flowRecordInsert(flowId, currentApprovalNode.getId(),
                "转交给【" + otherUser.getFirstName() + "】进行审核", comments);

        //推送消息
        pushService.sampleMessageOnlyUser("请您审批:" + record.getFlowName(), userId);
    }

    /**
     * 创建流程
     *
     * @param objectId 对象ID
     * @param type 审批类型
     * @param userId 指定下一审批人ID（为null则不指定）
     * @param moreFlowName 审批流名称
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void createFlow(Long objectId, String type, Long userId, String moreFlowName,
                           Long accntId, String approvalDetail) throws Exception {

        //1、查找审批流程
        Approval approval = approvalService.decideApproval(type);

        //2、查找审批节点
        ApprovalNode approvalNode = approvalNodeService.queryFirstApprovalNode(approval.getId());

        //3、查找用户列表
        List<User> userList = getNodeUserList(approvalNode, accntId);
        if (userList == null) {
            throw new ServiceException("APPROVAL-032");
        }
        String flag = "Y";
        //判断是否需要选择用户
        if (flag.equalsIgnoreCase(approvalNode.getMustSelectUser())) {
            if (userId == null) {
                throw new ApprovalNeedUserException(
                        "必须选择用户！[" + UserUtil.getUser().getId() + "],[" + approvalNode.getId() + "]");
            }
            boolean containUser = false;
            for (User user : userList) {
                if (user.getId().equals(userId)) {
                    containUser = true;
                }
            }
            if (!containUser) {
                throw new ServiceException("APPROVAL-019");
            }
        } else {
            if (userId != null) {
                throw new ApprovalNotNeedUserException("不需要选择用户！");
            }
        }

        //4、添加审批头信息
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        CoreUser user = UserUtil.getUser();
        Flow flow = new Flow();
        flow.setId(keyGenerateDao.keyGenerate());
        flow.setFlowObjId(objectId);
        //设置审批设置ID
        flow.setApprovalId(approval.getId());
        //审批设置节点Id
        flow.setApprovalNodeId(approvalNode.getId());
        flow.setFlowStatus("Running");
        flow.setFlowStart(dateFormat.format(new Date()));
        flow.setFlowNodeStart(dateFormat.format(new Date()));
        flow.setFlowStartPsnId(user.getId());
        flow.setAccntId(accntId);
        flow.setFlowObjDetail(approvalDetail);
        if (flag.equalsIgnoreCase(approvalNode.getMustSelectUser())) {
            //设置下一审批人
            flow.setFlowNodePsnId(userId);
        } else {
            //设置下一审批人
            if (userList.size() == 0) {
                throw new ServiceException("APPROVAL-033");
            }
            flow.setFlowNodePsnId(userList.get(0).getId());
        }
        String flowName = LovUtil.getLovName("APPROVAL_OBJECT_TYPE", type);
        if (moreFlowName != null && !"".equals(moreFlowName)) {
            flowName += "-" + moreFlowName;
        }
        flow.setFlowName(flowName);
        flowMapper.insert(flow);

        //5、将待审核用户，添加到用户审核列表中
        if (flag.equalsIgnoreCase(approvalNode.getMustSelectUser())) {
            flowUserService.insert(userId, flow.getId(), null);
            //推送消息
            pushService.sampleMessageForModule("请您审批:" + flowName, userId, flow.getId(), "Pending");
        } else {
            for (User userEntity : userList) {
                flowUserService.insert(userEntity.getId(), flow.getId(), null);
                //推送消息
                pushService.sampleMessageForModule("请您审批:" + flowName, userEntity.getId(), flow.getId(), "Pending");
            }
        }
    }


    /**
     * 获取节点审核用户列表 如果节点上的指定为”N“则按审批设置审批，为”Y“时走客户对应的”负责人员“
     */
    public List<User> getNodeUserList(ApprovalNode approvalNode, Long accntId) throws Exception {
        String flag = "Y";
        if (flag.equals(approvalNode.getIsSpecify())) {
            //查找用户列表
            List<User> userList = new ArrayList();

            /*获取客户所属的省区经理用户ID*/
            Account account = new Account();
            account.setId(accntId);
            Account accountObj = accountMapper.queryById(account);
            Position position = new Position();
            if (null == accountObj || null == accountObj.getPostnId()) {
                throw new ServiceException("APPROVAL-033");
            }
            position.setId(accountObj.getPostnId());
            Position positionObj = positionMapper.queryById(position);
            User userObj = new User();
            if (null == positionObj.getUserId()) {
                throw new ServiceException("APPROVAL-033");
            }
            userObj.setId(positionObj.getUserId());
            User userEntity = userService.queryById(userObj);
            userList.add(userEntity);

            return userList;

        } else {
            return usersSelectService
                    .queryUsers(approvalNode.getId(), UserUtil.getUser().getId());
        }
    }

}
